﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using BusinessLayer.Model.Repositories.Abstract;
using BusinessLayer.Model.Services.Abstract;

using BusinessLayer.Model.Services.Concrete;
using BusinessLayer.Model.Entities;
using DataAccess.Repositories;

namespace intecnologia.Admin
{
    public partial class Events : System.Web.UI.Page
    {
        IEventRepository _eventRepository = new EventRepository();
        ISessionService  _sessionService  = new SessionService();

        protected void Page_Load(object sender, EventArgs e)
        {
            if (_sessionService.SessionExpired())
                Response.Redirect("~/Admin/Default.aspx");

            BindDataList();
        }

        protected int EventsCount()
        {
            return _eventRepository.FetchAll().Count();
        }

        private void BindDataList()
        {
            dlEvents.DataSource = _eventRepository.FetchAll().OrderByDescending(ev => ev.Date);
            dlEvents.DataBind();
        }

        protected void btnAddEvents_Click(object sender, EventArgs e)
        {
            Response.Redirect("~/Admin/EditEvents.aspx");
        }

        protected void dlEvents_ItemCommand(object source, DataListCommandEventArgs e)
        {
            if (e.CommandName == "EditEvent")
                EditEvent(new Guid(dlEvents.DataKeys[e.Item.ItemIndex].ToString()));

            else if (e.CommandName == "DeleteEvent")
                DeleteEvent(new Guid(dlEvents.DataKeys[e.Item.ItemIndex].ToString()));
        }

        private void DeleteEvent(Guid eventID)
        {
            Event newsToDelete = _eventRepository.FetchByID(eventID);

            _eventRepository.DeleteOnSubmit(newsToDelete);
            _eventRepository.SubmitChanges();

            BindDataList();
        }

        private void EditEvent(Guid eventID)
        {
            Response.Redirect("~/Admin/EditEvents.aspx?edit=true&id=" + eventID.ToString());
        }
    }
}
